from datetime import timedelta, datetime
from typing import Dict, Any

import jwt
from fastapi import HTTPException
from starlette import status

from common.RsaUtil import RsaUtil
from common.GlobalConfig import config
from modules.http_resp import ResponseFail


class JwtUtil:

    @staticmethod
    def verify_password(plain_password, hashed_password):
        return RsaUtil.verify(plain_password,  hashed_password)

    @staticmethod
    def create_access_token(data: dict, expires_delta: timedelta  = None):
        to_encode = data.copy()
        expire = datetime.now() + (expires_delta or timedelta(minutes=15))
        to_encode.update({"exp": expire})
        encoded_jwt = jwt.encode(to_encode, config.SECRET_KEY, algorithm=config.ALGORITHM)
        return encoded_jwt

    @staticmethod
    def decode_access_token(token: str) -> Dict[str, Any]:
        try:
            payload = jwt.decode(
                token,
                config.SECRET_KEY,
                algorithms=[config.ALGORITHM]
            )
            # 可以在这里做额外的校验，比如检查 exp 是否过期（虽然 jwt 已自动处理）
            return payload
        except jwt.ExpiredSignatureError:
            raise ResponseFail("Token 已过期")
        except jwt.PyJWTError:
            raise ResponseFail("无效的 Token")